//package com.plian.system.service.tb.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.common.status.CheckStatus;
//import com.plian.system.config.YthTaskObserver;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.tb.TripleStatusConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.entity.tb.TripleSystem;
//import com.plian.system.mapper.tb.TripleSystemMapper;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.tb.ITripleSystemService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.service.yth.IRegulationService;
//import com.plian.system.vo.tb.TripleSystemVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.tb.TripleSystemWrapper;
//import lombok.AllArgsConstructor;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * @Author: Take-off
// * @Description: TODO
// * @Date: 2022/12/23 10:57 AM
// * @Version: 1.0
// **/
//@Service
//@AllArgsConstructor
//public class TripleSystemServiceImpl extends BaseServiceImpl<TripleSystemMapper, TripleSystem> implements ITripleSystemService, BaseFlowService {
//
//    private FormWorkflowService formWorkflowService;
//
//    private IFormCodeService formCodeService;
//
//    private TripleSystemWrapper tripleSystemWrapper;
//
//    private final FileService fileService;
//
//    private IRegulationService iRegulationService;
//
//    private IOrgService orgService;
//
//    private ISysUserService userService;
//
//    @Override
//    public boolean saveOrUpdate(TripleSystem tripleSystem) {
//        boolean flag = false;
//        if (!Optional.ofNullable(tripleSystem.getSystemStatus()).isPresent()) {
//            tripleSystem.setSystemStatus(TripleStatusConstant.UNREVIEWED);
//        }
//        if (!Optional.ofNullable(tripleSystem.getId()).isPresent()) {
//            flag = true;
//            //todo code
//            tripleSystem.setCode(formCodeService.getCode(FormTypeConstant.PF_TRIPLE_SYSTEM));
//            tripleSystem.setSystemNumber(formCodeService.getCodeName(FormTypeConstant.PF_TRIPLE_SYSTEM));
//            tripleSystem.setFormType(String.valueOf(FormTypeConstant.PF_TRIPLE_SYSTEM));
//        }
//        boolean result = super.saveOrUpdate(tripleSystem);
//        if (flag){
//            fileService.saveAll(String.valueOf(tripleSystem.getId()), tripleSystem.getDocList());
//        }else {
//            fileService.edit(String.valueOf(tripleSystem.getId()), tripleSystem.getDocList());
//        }
//        if (StringUtil.isNotBlank(tripleSystem.getAttachIds())){
//            fileService.upYthFile(tripleSystem.getAttachIds(),String.valueOf(tripleSystem.getId()));
//        }
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean changeStatus(List<Long> ids,int type) {
//        List<TripleSystem> tripleSystems = new ArrayList<>();
//        for (Long id : ids) {
//            TripleSystem tripleSystem = getById(id);
//            if (tripleSystem == null) {
//                return false;
//            }else {
//                tripleSystem.setSystemStatus(type);
//                tripleSystems.add(tripleSystem);
//            }
//        }
//        boolean result = super.updateBatchById(tripleSystems);
//        return result;
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            TripleSystem tripleSystem = getById(id);
//            if (tripleSystem == null) {
//                return false;
//            } else if (tripleSystem.getStatus() != null &&
//                    (tripleSystem.getStatus() != FormStatusConstant.STASH && tripleSystem.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//        return super.deleteLogic(ids);
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState,String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<TripleSystem> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(TripleSystem::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<TripleSystem> tripleSystems = list(queryWrapper);
//        List<TripleSystemVO> tripleSystemVOS = tripleSystemWrapper.entityToVO(tripleSystems);
//        List<PageData> pageDataList = new ArrayList<>();
//        try{
//            if (CollectionUtil.isNotEmpty(tripleSystemVOS)){
//                for (TripleSystemVO vo : tripleSystemVOS){
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getFillingUnitName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getFillingUnitId());
//                    pd.put("formType", FormTypeConstant.PF_TRIPLE_SYSTEM);
//                    pd.put("orgName", vo.getFillingUnitName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.PF_TRIPLE_SYSTEM);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id          主键
//     * @param updateStatus  更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            TripleSystem tripleSystem = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH){
//                tripleSystem.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                tripleSystem.setApprovedTime(now);
//            }
//            tripleSystem.setStatus(updateStatus);
//            updateById(tripleSystem);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean submit(TripleSystem tripleSystem) {
//        boolean result = saveOrUpdate(tripleSystem);
//        return result;
//    }
//
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String saveTripleSystemList(String data){
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<TripleSystem> dataList = JSON.parseArray(data, TripleSystem.class);
//        if (CollectionUtil.isNotEmpty(dataList)){
//            //根据datasourceIds 查询出所有的数据
//            List<TripleSystem> list = list(new LambdaQueryWrapper<TripleSystem>().in(TripleSystem::getDataSourceId, dataList.stream().map(TripleSystem::getDataSourceId).toArray()));
//            //如果数据库中有数据，就更新，没有就新增
//            for (TripleSystem entity:dataList){
//                //id重复略过
//                if (CollectionUtil.isNotEmpty(list)){
//                    List<String> olIds = list.stream().map(TripleSystem::getDataSourceId).collect(Collectors.toList());
//                    String dataSourceId = entity.getDataSourceId();
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)){
//                        for (TripleSystem oldEntity:list){
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())){
//                                //判断status是否为0，如果是0，就更新，不是0，就不更新
//                                if (CheckStatus.checkCode(oldEntity.getStatus())){
//                                    successIds.add(dataSourceId);
//                                    entity.setId(oldEntity.getId());
//                                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                                    saveOrUpdate(entity);
//                                    list.remove(oldEntity);
//                                    break;
//                                }else {
//                                    failIds.add(dataSourceId);
//                                    failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
//                                    break;
//                                }
//                            }
//                        }
//                    }else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//                        saveOrUpdate(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                }else {
//                    //如果数据库中没有数据，就新增
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                    saveOrUpdate(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        } else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    @Override
//    @YthTaskObserver
//    public boolean saveTripleSystem(String date) {
//        boolean flag = true;
//        Date start = DateUtil.parse(date, DateUtil.PATTERN_DATE);
//        //获取数据
////        List<TripleSystem> tripleSystems = iRegulationService.getAllProject(start, DateUtil.plusDays(start, 1));
//        List<TripleSystem> tripleSystems = iRegulationService.getAllProject(null, null);
////        tripleSystems = tripleSystems.stream().filter(m -> m.getSystemName().equals("投资制度1")).collect(Collectors.toList());
//        remove(Wrappers.<TripleSystem>lambdaQuery().eq(TripleSystem::getDataSource,3));
//
//        Map<String, String> orgSourceIds = orgService.getSourceId();
//        Map<String, String> userSourceIds = userService.getSourceId();
//        if (CollectionUtil.isNotEmpty(tripleSystems)) {
//            List<TripleSystem> oldReforms = list(Wrappers.<TripleSystem>lambdaQuery().eq(TripleSystem::getDataSource, YthConstant.DATA_NINGBO)
//                    .in(TripleSystem::getDataSourceId, tripleSystems.stream().map(TripleSystem::getDataSourceId).collect(Collectors.toList())));
//            for (TripleSystem tripleSystem : tripleSystems) {
//                String orgId = orgSourceIds.get(tripleSystem.getFillingUnitId());
//                if (StringUtils.isNotBlank(orgId)) {
//                    tripleSystem.setFillingUnitId(orgId);
//                    tripleSystem.setCreateCompanyId(orgId);
//                }
//                String userId = userSourceIds.get(tripleSystem.getReportUser());
//                if (StringUtils.isNotBlank(userId)) {
//                    tripleSystem.setReportUser(userId);
//                }
//                tripleSystem.setStatus(FormStatusConstant.FINISH);
//                if (CollectionUtil.isNotEmpty(oldReforms)) {
//                    Optional<TripleSystem> reformOptional = oldReforms.stream().filter(m -> tripleSystem.getDataSourceId().equals(m.getDataSourceId())).findFirst();
//                    if (reformOptional.isPresent()) {
//                        TripleSystem oldReform = reformOptional.get();
//                        oldReform.setFillingUnitId(tripleSystem.getFillingUnitId());
//                        oldReform.setReportUser(tripleSystem.getReportUser());
//                        oldReform.setReportTime(tripleSystem.getReportTime());
//                        oldReform.setSystemNumber(tripleSystem.getSystemNumber());
//                        oldReform.setSystemName(tripleSystem.getSystemName());
//                        oldReform.setSystemType(tripleSystem.getSystemType());
//                        oldReform.setSystemUpdateTime(tripleSystem.getSystemUpdateTime());
//                        oldReform.setEffectTime(tripleSystem.getEffectTime());
//                        oldReform.setFailureTime(tripleSystem.getFailureTime());
//                        oldReform.setSystemText(tripleSystem.getSystemText());
//                        oldReform.setSystemStatus(TripleStatusConstant.LATER);
//                        flag = updateById(oldReform);
//                    } else {
//                        flag = submit(tripleSystem);
//                    }
//                } else {
//                    flag = submit(tripleSystem);
//                }
//            }
//        }
//        return flag;
//    }
//}
